<template>
  <div class="app-container">
    <el-main>
      <div class="search">
        <el-form ref="searchForm" :inline="true" size="mini" :model="searchForm" class="form-inline">
          <el-form-item label="姓名：" prop="name">
            <el-input v-model.trim="searchForm.name" clearable placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="角色：" prop="role_id">
            <el-select v-model="searchForm.role_id" filterable clearable placeholder="请选择角色">
              <el-option v-for="item in roleSearchList" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px">{{ item.status == 1 ? '' : '已禁用' }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="searchSubmit('searchForm')">搜索</el-button>
            <el-button type="info" plain @click="searchReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="20" type="flex" align="center">
        <el-col>
          <el-button v-permission="'user_add'" type="primary" size="mini" @click.native="showAdd()">新增</el-button>
        </el-col>
      </el-row>

      <el-table
        ref="multipleTable"
        v-loading="tabLoading"
        stripe
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        border
        size="mini"
        :default-sort="{prop: 'date', order: 'descending'}"
        highlight-current-row
        row-key="id"
        @selection-change="handleSelectionChange"
        :max-height="tableMaxHeight"
      >
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" width="120" show-overflow-tooltip/>
        <el-table-column prop="departmen_list_name" label="部门(岗位)" show-overflow-tooltip min-width="200"/>
        <!-- <el-table-column prop="postname" label="岗位" show-overflow-tooltip min-width="100" /> -->
        <el-table-column prop="name" label="姓名" width="120" show-overflow-tooltip/>
        <el-table-column prop="sex" label="性别" width="60" show-overflow-tooltip/>
        <el-table-column prop="mobile" label="联系号码" width="120" show-overflow-tooltip/>
        <!-- <el-table-column prop="idCard" label="身份证号" width="200" show-overflow-tooltip />
        <el-table-column prop="idCard" label="入职时间" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="试用期" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="是否转正" show-overflow-tooltip />
        <el-table-column prop="idCard" label="转正日期" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="合同签订时间" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="年限" width="80" show-overflow-tooltip />
        <el-table-column prop="idCard" label="保密协议是否签字" show-overflow-tooltip />
        <el-table-column prop="idCard" label="实际参保时间" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="参保公司" width="200" show-overflow-tooltip />
        <el-table-column prop="idCard" label="参保公司变更" width="200" show-overflow-tooltip />
        <el-table-column prop="idCard" label="学历" width="80" show-overflow-tooltip />
        <el-table-column prop="idCard" label="出生年月" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="生日" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="婚姻情况" show-overflow-tooltip />
        <el-table-column prop="idCard" label="司龄" width="80" show-overflow-tooltip />
        <el-table-column prop="idCard" label="户籍地址" width="250" show-overflow-tooltip />
        <el-table-column prop="idCard" label="家庭住址" width="250" show-overflow-tooltip />
        <el-table-column prop="idCard" label="紧急联系电话" width="120" show-overflow-tooltip />
        <el-table-column prop="idCard" label="员工入职表" width="150" show-overflow-tooltip />
        <el-table-column prop="idCard" label="身份证复印件" width="150" show-overflow-tooltip />
        <el-table-column prop="idCard" label="就业证" width="100" show-overflow-tooltip />
        <el-table-column prop="idCard" label="就业花名册" width="100" show-overflow-tooltip />
        <el-table-column prop="idCard" label="其他" width="100" show-overflow-tooltip />
        <el-table-column prop="idCard" label="离职时间" width="120" show-overflow-tooltip /> -->

        <el-table-column prop="role_names" label="角色" min-width="230">
          <template slot-scope="scope">
            <el-tag v-for="(item,index) in scope.row.role_names" :key="index" class="names-tag" size="small">{{
                item
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="index_page" label="首页" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="mini_index_page" label="小程序首页" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="sort" label="排序" width="80" show-overflow-tooltip sortable fixed="right"/>
        <el-table-column prop="status" label="启用" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              v-permission-disabled="'user_switch'"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="390px" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation">
              <el-button-group>
                <el-button
                  v-permission="'user_edit'"
                  type="primary"
                  icon="el-icon-edit-outline"
                  size="mini"
                  @click.native="showEdit(scope.row)"
                >编辑
                </el-button>
                <el-button v-permission="'user_set_role'" type="primary" icon="el-icon-user" size="mini"
                           @click.native="showSetRole(scope.row)"
                >配置角色
                </el-button>
                <el-button v-permission="'user_reset_password'" type="warning" icon="el-icon-refresh" size="mini"
                           @click.native="resetPassword(scope.row.id)"
                >重置密码
                </el-button>
                <!-- <el-button type="success" icon="el-icon-user" size="small" @click.native="inviteUser(scope.row.id)" v-permission="'user_invite'" v-if="scope.row.is_joined==0">邀请</el-button> -->
                <el-button v-permission="'user_del'" type="danger" icon="el-icon-delete" size="mini"
                           @click.native="delVer(scope.row.id)"
                >删除
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页数据 -->
      <el-pagination
        :current-page.sync="current"
        :page-sizes="[10, 20, 50, 100, 200, 500]"
        :page-size="listParams.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-main>

    <el-dialog :close-on-click-modal="false" title="配置角色" center :visible.sync="dialogCU" width="40%"
               @close="dialogCUClose('cuForm')"
    >
      <el-form ref="cuForm" v-loading="dialogCULoading" :rules="cuRules" :model="cuForm" label-width="120px" center>
        <el-form-item label="角色" prop="role_ids">
          <el-col :span="20">
            <el-select
              v-model="cuForm.role_ids"
              filterable
              placeholder="请选择角色"
              style="width:100%"
              multiple
              @visible-change="visibleChangeRole"
              @change="changeRole"
              @remove-tag="removeRole"
            >
              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"
                         :disabled="item.status==0 || item.hide==1"
              >
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px;margin-right: 30px;">首页：{{
                    item.index_page
                  }}</span>
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="用户首页" prop="index_role_id">
          <el-col :span="20">
            <el-select v-model="cuForm.index_role_id" filterable clearable placeholder="请选择用户首页" style="width:100%"
                       no-data-text="请先选择角色"
            >
              <el-option v-for="item in roleIndexPageList" :key="item.id" :label="item.index_page" :value="item.id">
                <span style="float: left">{{ item.index_page }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px;">属于：{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="小程序首页" prop="mini_index_role_id">
          <el-col :span="20">
            <el-select v-model="cuForm.mini_index_role_id" filterable clearable placeholder="请选择小程序首页"
                       style="width:100%" no-data-text="请先选择角色"
            >
              <el-option v-for="item in roleMiniIndexPageList" :key="item.id" :label="item.mini_index_page"
                         :value="item.id"
              >
                <span style="float: left">{{ item.mini_index_page }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px;">属于：{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCU=false">取 消</el-button>
        <el-button type="primary" @click.native="onSubmitSetRole(cuForm.id)">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :title="(cuFormTwo.id?'编辑':'新增')"
      center
      :visible.sync="dialogCUTwo"
      width="85%"
      @close="dialogCUClose('cuFormTwo')"
    >
      <el-form
        ref="cuFormTwo"
        v-loading="dialogCULoadingTwo"
        :rules="cuRulesTwo"
        :model="cuFormTwo"
        label-width="120px"
        center
      >
        <el-row class="row-bg">
          <el-col :span="10">
            <el-form-item label="账号" prop="username">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.username" clearable placeholder="请输入账号"
                          :disabled="cuFormTwo.id!=null"
                />
              </el-col>
            </el-form-item>
            <el-form-item v-if="!cuFormTwo.id" label="密码" prop="password">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.password" clearable placeholder="不填则为默认密码"/>
              </el-col>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.name" clearable placeholder="请输入姓名"/>
              </el-col>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-col :span="24">
                <el-radio-group v-model="cuFormTwo.sex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.mobile" clearable placeholder="请输入手机"/>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="身份证号" prop="id_no">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuFormTwo.id_no" placeholder="请输入身份证号" />
							</el-col>
						</el-form-item>
						<el-form-item label="生日">
							<el-col :span="24">
								<el-date-picker clearable v-model="cuFormTwo.birth" type="date"
									placeholder="选择生日"
									format="yyyy年MM月dd日"
									value-format="yyyy-MM-dd HH:mm:ss"
									style="width:100%" >
								</el-date-picker>
							</el-col>
						</el-form-item>
						<el-form-item label="学历" prop="degree">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.degree">
									<el-radio label="本科">本科</el-radio>
									<el-radio label="大专">大专</el-radio>
									<el-radio label="高中">高中</el-radio>
									<el-radio label="初中">初中</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="婚姻状况" prop="marriage">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.marriage">
									<el-radio label="已婚">已婚</el-radio>
									<el-radio label="已婚已育">已婚已育</el-radio>
									<el-radio label="未婚">未婚</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="户籍" prop="household_registration">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuFormTwo.household_registration" placeholder="请输入户籍" />
							</el-col>
						</el-form-item>
						<el-form-item label="家庭住址" prop="home_address">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuFormTwo.home_address" placeholder="请输入家庭住址" />
							</el-col>
						</el-form-item>
						<el-form-item label="紧急电话" prop="urgent_phone">
							<el-col :span="24">
								<el-input clearable v-model.trim="cuFormTwo.urgent_phone" placeholder="请输入紧急电话" />
							</el-col>
						</el-form-item> -->

            <el-form-item label="邮箱" prop="email">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.email" clearable placeholder="请输入邮箱"/>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="2">
            <el-form-item label="状态" prop="status">
              <el-col :span="24">
                <el-radio-group v-model="cuFormTwo.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-col :span="24">
                <el-input v-model.trim="cuFormTwo.sort" type="number" placeholder="请输入排序"/>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="入职日期">
							<el-col :span="24">
								<el-date-picker clearable v-model="cuFormTwo.onboarding_at" type="date"
									placeholder="选择入职日期"
									format="yyyy年MM月dd日"
									value-format="yyyy-MM-dd HH:mm:ss"
									style="width:100%" >
								</el-date-picker>
							</el-col>
						</el-form-item>
						<el-form-item label="试用日期（月）" prop="probation_period">
							<el-col :span="24">
								<el-input-number v-model.trim="cuFormTwo.probation_period" min="1" placeholder="请输入试用期" />
							</el-col>
						</el-form-item>
						<el-form-item label="是否转正" prop="positive">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.positive">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="转正日期" prop="positive_at">
							<el-col :span="24">
								<el-date-picker clearable v-model="cuFormTwo.positive_at" type="date"
									placeholder="选择转正日期"
									format="yyyy年MM月dd日"
									value-format="yyyy-MM-dd HH:mm:ss"
									style="width:100%" >
								</el-date-picker>
							</el-col>
						</el-form-item>
						<el-form-item label="合同签订时间" prop="contract_confirm">
							<el-col :span="24">
								<el-date-picker clearable v-model="cuFormTwo.contract_confirm"
									type="daterange"
									start-placeholder="开始日期"
      								end-placeholder="结束日期"
									format="yyyy年MM月dd日"
									value-format="yyyy-MM-dd HH:mm:ss"
									style="width:100%" >
								</el-date-picker>
							</el-col>
						</el-form-item>
						<el-form-item label="合同年限" prop="contract_period">
							<el-col :span="24">
								<el-input-number v-model.trim="cuFormTwo.contract_period" min="1" placeholder="请输入合同年限" />
							</el-col>
						</el-form-item>
						<el-form-item label="是否签订保密协议" prop="contract_secrecy">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.contract_secrecy">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="司龄" prop="company_age">
							<el-col :span="24">
								<el-input v-model.trim="cuFormTwo.company_age"  placeholder="请输入司龄" />
							</el-col>
						</el-form-item>
						<el-form-item label="是否有入职表" prop="onboarding_table">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.onboarding_table">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item>
						<el-form-item label="是否有入职身份证复印件" prop="onboarding_copy_id_card">
							<el-col :span="24">
								<el-radio-group v-model="cuFormTwo.onboarding_copy_id_card">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-col>
						</el-form-item> -->
            <el-form-item label="角色" prop="role_ids">
              <el-col :span="24">
                <el-select
                  v-model="cuFormTwo.role_ids"
                  filterable
                  placeholder="请选择角色"
                  style="width:100%"
                  multiple
                  @visible-change="visibleChangeRoleTwo"
                  @change="changeRoleTwo"
                  @remove-tag="removeRoleTwo"
                >
                  <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"
                             :disabled="item.status==0 || item.hide==1"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 12px;margin-right: 30px;"
                    >首页：{{ item.index_page }}</span>
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="用户首页" prop="index_role_id">
              <el-col :span="24">
                <el-select v-model="cuFormTwo.index_role_id" filterable clearable placeholder="请选择用户首页"
                           style="width:100%" no-data-text="请先选择角色"
                >
                  <el-option v-for="item in roleIndexPageListTwo" :key="item.id" :label="item.index_page"
                             :value="item.id"
                  >
                    <span style="float: left">{{ item.index_page }}</span>
                    <span style="float: right; color: #8492a6; font-size: 12px;">属于：{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="小程序首页" prop="mini_index_role_id">
              <el-col :span="24">
                <el-select
                  v-model="cuFormTwo.mini_index_role_id"
                  filterable
                  clearable
                  placeholder="请选择小程序首页"
                  style="width:100%"
                  no-data-text="请先选择角色"
                >
                  <el-option v-for="item in roleMiniIndexPageListTwo" :key="item.id" :label="item.mini_index_page"
                             :value="item.id"
                  >
                    <span style="float: left">{{ item.mini_index_page }}</span>
                    <span style="float: right; color: #8492a6; font-size: 12px;">属于：{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item> -->
            <el-form-item label="部门职位" prop="departments">
              <el-row type="flex" style="justify-content: flex-end;">
                <el-button type="text" @click.native="showChooseDepartment(cuFormTwo.department_list)">关联部门</el-button>
              </el-row>
              <el-table :data="cuFormTwo.department_list" stripe size="small" style="width: 100%;" max-height="380"
                        border
              >
                <el-radio/>
                <el-table-column prop="main" label="主部门" align="center">
                  <template slot-scope="scope">
                    <el-radio
                      v-model="mainDepartmentId"
                      :label="scope.row.id"
                      @click.native.prevent="setMainDepartment(scope.row)"
                    >{{ '' }}
                    </el-radio>
                  </template>
                </el-table-column>
                <el-table-column prop="business_head" label="负责人" align="center">
                  <template slot-scope="scope">
                    <el-checkbox
                      v-model="scope.row.business_head"
                      :disabled="!scope.row.business"
                    >{{ '' }}
                    </el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="部门" align="center" show-overflow-tooltip min-width="170"/>
                <el-table-column prop="job" label="职位" align="center" show-overflow-tooltip min-width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.job" size="small"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50" align="center" fixed="right">
                  <template slot-scope="{row,$index}">
                    <el-button type="text" size="small"
                               @click.native.prevent="deleteRow($index,cuFormTwo.department_list)"
                    >移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCUTwo=false">取 消</el-button>
        <el-button type="primary" @click.native="onSubmit(cuFormTwo.id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <transition
			mode="out-in"
			@before-enter="beforeEnter"
			@enter="enter"

			@before-leave="beforeLeave"
			@leave="leave"
			:css="false">

		</transition> -->

    <el-dialog :close-on-click-modal="false" title="部门职位" center :visible.sync="dialogCUThree" width="85%"
               @close="dialogCUClose('cuFormThree')"
    >
      <el-form
        ref="cuFormThree"
        v-loading="dialogCULoadingThree"
        :model="cuFormThree"
        label-width="120px"
        center
      >
        <el-row class="row-bg">
          <el-col :span="11">
            <el-form-item label="部门">
              <el-tree
                ref="departmentTree"
                node-key="id"
                :data="departmentList"
                :check-strictly="true"
                :default-expand-all="true"
                :expand-on-click-node="false"
                style="margin-top:20px;max-height: 410px;overflow-y: auto;"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node" style="width:100%">
                  <div class="flex justify-between align-center">
                    <div>
                      <span>{{ data.name }}</span>
                    </div>
                    <div class="margin-left-xs">
                      <el-button type="text" size="mini" @click="() => chooseOneDepartment(data)">
                        选择
                      </el-button>
                    </div>
                  </div>
                </span>
              </el-tree>
            </el-form-item>

          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="已选">
              <el-table :data="cuFormThree.department_list" stripe size="small" style="width: 100%;" max-height="380"
                        border
              >
                <el-table-column prop="name" label="部门" align="center" show-overflow-tooltip min-width="170"/>
                <el-table-column prop="job" label="职位" align="center" show-overflow-tooltip min-width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.job" size="small"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50" align="center" fixed="right">
                  <template slot-scope="{row,$index}">
                    <el-button type="text" size="small"
                               @click.native.prevent="deleteRow($index,cuFormThree.department_list)"
                    >移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="dialogCUThree=false">取 消</el-button>
        <el-button type="primary" @click.native="choosedDepartment()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  list,
  role_list,
  set_role,
  add,
  edit,
  del,
  change_status,
  reset_password,
  department_for_choose,
  send_invite
} from '@/api/system/user.js'
import {
  Message
} from 'element-ui'
import {
  cloneDeep
} from 'lodash'

const reg_mobile = /^1(3|4|5|6|7|8|9)\d{9}$/
const reg_email = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/
const reg_idno = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!reg_mobile.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    var validateEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!reg_email.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }

    var validateIdNo = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!reg_idno.test(value)) {
        callback(new Error('请输入正确的身份证号'))
      } else {
        callback()
      }
    }
    return {
      tableMaxHeight: 0,
      // search form
      searchForm: {
        name: null,
        username: null,
        role_id: null
      },
      // page option
      total: null, // 总页数
      current: 1, // 当前页

      // list table
      tableData: [], // 列表数据
      selectIds: [], // 多选选项id
      mainDepartmentId: '',
      listParams: {
        name: null,
        username: null,
        role_id: null,
        page: 1,
        page_size: 10
      }, // list参数
      tabLoading: true,

      // CU dialog
      dialogCULoading: false,
      dialogCU: false, // 增修弹框显示
      cuForm: {
        id: null,
        role_ids: [],
        index_role_id: null,
        mini_index_role_id: null
      },
      cuRules: {
        role_ids: [{
          required: true,
          message: '请选择角色',
          trigger: 'change'
        }],
        index_role_id: [{
          required: true,
          message: '请选择用户首页',
          trigger: 'change'
        }]
      },

      // CU dialog two
      dialogCULoadingTwo: false,
      dialogCUTwo: false, // 增修弹框显示
      cuFormTwo: {
        id: null,
        name: null,
        username: null,
        password: null,
        mobile: null,
        email: null,
        sex: '男',
        status: 0,
        sort: 1,
        role_ids: [],
        index_role_id: null,
        mini_index_role_id: null
      },
      cuRulesTwo: {
        name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          validator: validateMobile,
          trigger: 'blur'
        }],
        id_no: [{
          validator: validateIdNo,
          trigger: 'blur'
        }],
        urgent_phone: [{
          validator: validateMobile,
          trigger: 'blur'
        }],
        role_ids: [{
          required: true,
          message: '请选择角色',
          trigger: 'change'
        }],
        index_role_id: [{
          required: true,
          message: '请选择用户首页',
          trigger: 'change'
        }]
      },

      roleList: [],
      roleSearchList: [],
      roleIndexPageList: [],
      roleMiniIndexPageList: [],
      roleIndexPageListTwo: [],
      roleMiniIndexPageListTwo: [],
      roles: {},

      departmentList: [],

      // CU dialog
      dialogCULoadingThree: false,
      dialogCUThree: false, // 增修弹框显示
      cuFormThree: {
        department_list: []
      }
    }
  },
  computed: {},
  created() {
    this.tableMaxHeight = (document.documentElement.clientHeight || document.body.clientHeight) - 210
    this.getList()
    this.getRoleList()
    this.getDepartmentForChoose()
  },
  mounted: function() {
  },
  methods: {
    setMainDepartment(row) {
      this.mainDepartmentId = row.id
      this.cuFormTwo.department_list.forEach(e => e.main = false)
      row.main = true
    },
    inviteUser(id) {
      this.$confirm('您确定要发送邀请短信吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          send_invite({ id: id })
            .then(res => {
              const {
                code,
                message
              } = res
              if (code === 200) {
                Message({
                  message: '邀请短信已发送',
                  type: 'success',
                  duration: 1000
                })
              }
            })
        })
        .catch()
    },
    // 新增弹出框
    showAdd() {
      this.dialogCUTwo = true
      this.dialogCULoadingTwo = false
      this.resetFormTwo()
      this.$refs['cuFormTwo'] && this.$refs['cuFormTwo'].resetFields()
    },
    // 编辑弹出框
    showEdit(row) {
      this.cuFormTwo = Object.assign({}, row)
      // 兼容未设置部门的情况下编辑报错
      let mainDepart = this.cuFormTwo.department_list.find(e => e.main)
      this.mainDepartmentId = mainDepart == null ? '' : mainDepart.id
      this.cuFormTwo.role_ids = (row.role_ids ? (row.role_ids.split(',').map(item => parseInt(item))) : [])
      this.cuFormTwo.index_role_id = row.index_role_id
      this.cuFormTwo.mini_index_role_id = row.mini_index_role_id
      this.setRoleIndexPageList(true, 'cuFormTwo')
      this.dialogCUTwo = true
      this.dialogCULoadingTwo = false
    },
    showChooseDepartment(department_list) {
      this.cuFormThree.department_list = cloneDeep(department_list || [])
      this.dialogCUThree = true
      this.dialogCULoadingThree = false
    },
    // 配置角色弹出框
    showSetRole(row) {
      this.cuForm.id = row.id
      this.cuForm.role_ids = (row.role_ids ? (row.role_ids.split(',').map(item => parseInt(item))) : [])
      this.cuForm.index_role_id = row.index_role_id
      this.cuForm.mini_index_role_id = row.mini_index_role_id
      this.setRoleIndexPageList(true)
      this.dialogCU = true
      this.dialogCULoading = false
    },
    // 关闭弹窗
    dialogCUClose(formName) {
      switch (formName) {
        case 'cuForm':
          this.$refs['cuForm'].clearValidate()
          this.resetForm()
          break
        case 'cuFormTwo':
          this.$refs['cuFormTwo'].clearValidate()
          this.resetFormTwo()
          break
        case 'cuFormThree':
          this.resetFormThree()
          break
      }
    },

    resetForm() {
      this.cuForm = {
        id: null,
        role_ids: [],
        index_role_id: null,
        mini_index_role_id: null
      }
    },
    resetFormTwo() {
      this.cuFormTwo = {
        id: null,
        name: null,
        username: null,
        password: null,
        mobile: null,
        email: null,
        sex: '男',
        status: 0,
        sort: 1,
        role_ids: [],
        index_role_id: null,
        mini_index_role_id: null
      }
    },
    resetFormThree() {
      this.cuFormThree = {
        department_list: []
      }
    },
    // 提交数据 设置角色
    onSubmitSetRole(id) {
      // 表单校验
      this.$refs.cuForm.validate(valid => {
        // ~ 校验通过
        if (valid) {
          var obj = Object.assign({}, this.cuForm)

          // 显示loading
          this.dialogCULoading = true

          // ~~ 设置角色
          this.setRole(obj)
        } else {
          // ~ 不通过
          return false
        }
      })
    },
    // 提交数据 增、改
    onSubmit(id) {
      // 表单校验
      this.$refs.cuFormTwo.validate(valid => {
        // ~ 校验通过
        if (valid) {
          var obj = Object.assign({}, this.cuFormTwo)

          // 显示loading
          this.dialogCULoadingTwo = true

          this.cuFormTwo.department_list = this.cuFormTwo.department_list || []

          // ~~ 修改
          if (id) {
            this.onEdit(obj)
          } else {
            // ~~ 添加
            delete obj.id
            this.onAdd(obj)
          }
        } else {
          // ~ 不通过
          return false
        }
      })
    },

    // 配置角色
    setRole(obj) {
      // 小程序首页不进行保存
      obj.mini_index_role_id = null
      return set_role(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCU = false
            this.getList()
          }
          this.dialogCULoading = false
        })
        .catch(() => {
          this.dialogCULoading = false
        })
    },

    // 添加
    onAdd(obj) {
      // 小程序首页不进行保存
      obj.mini_index_role_id = null
      return add(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCUTwo = false
            this.getList()
          }
          this.dialogCULoadingTwo = false
        })
        .catch(() => {
          this.dialogCULoadingTwo = false
        })
    },

    // 编辑
    onEdit(obj) {
      // 小程序首页不进行保存
      obj.mini_index_role_id = null
      return edit(obj)
        .then(res => {
          const {
            code,
            message
          } = res
          if (code === 200) {
            Message({
              message,
              type: 'success',
              duration: 1000
            })
            this.dialogCUTwo = false
            this.getList()
          }
          this.dialogCULoadingTwo = false
        })
        .catch(() => {
          this.dialogCULoadingTwo = false
        })
    },
    // 删除
    delVer(id = false) {
      this.$confirm('确认要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = id ? [id] : this.selectIds
          del(ids).then(res => {
            const {
              code,
              date,
              message
            } = res
            this.getList()
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch()
    },
    // 是否启用
    changeStatus(status, row) {
      const flag = +!status
      this.$confirm('确认要' + (status ? '启用' : '禁用') + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          const ids = [row.id]
          return change_status(ids, status).then(res => {
            const {
              message
            } = res
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch(() => {
        row.status = flag
      })
    },
    resetPassword(id) {
      this.$confirm('确认要重置密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      })
        .then(() => {
          reset_password(id).then(res => {
            const {
              code,
              date,
              message
            } = res
            Message({
              message,
              type: 'success',
              duration: 1000
            })
          })
        }).catch()
    },
    // 获得table列表
    getList() {
      this.tabLoading = true
      return list(this.listParams)
        .then(res => {
          const {
            data: {
              records,
              total
            }
          } = res
          this.tableData = records.map(item => {
            if (item.role_names) {
              item.role_names = item.role_names.split(',')
            } else {
              item.role_names = []
            }

            if (item.department_list) {
              item.departmen_list_name = item.department_list.map((item, index) => {
                return item.name + (item.job ? ('(' + item.job + ')') : '')
              }).join('、')
            }
            return item
          })
          this.$nextTick(() => {
            this.$refs.multipleTable.doLayout()
          })
          this.total = total
          this.tabLoading = false
        })
        .catch(() => {
          this.tabLoading = false
        })
    },
    // 部门待选列表
    getDepartmentForChoose() {
      return department_for_choose()
        .then(res => {
          this.departmentList = res.data
        })
    },
    // 获得角色待选项列表
    getRoleList() {
      return role_list()
        .then(res => {
          const roles = {}
          cloneDeep(res.data).forEach(item => {
            roles['_' + item.id] = item
          })
          this.roles = roles
          this.roleList = cloneDeep(res.data)
          this.roleSearchList = cloneDeep(res.data)
        })
    },
    setRoleIndexPageList(first = false, form = 'cuForm', canRemove = true, removeId) {
      const that = this
      if (!first) {
        if (form === 'cuForm') {
          that.cuForm.index_role_id = null
          that.cuForm.mini_index_role_id = null
        }
        if (form === 'cuFormTwo') {
          that.cuFormTwo.index_role_id = null
          that.cuFormTwo.mini_index_role_id = null
        }
      }

      if (form === 'cuForm') {
        that.roleIndexPageList = []
        that.roleMiniIndexPageList = []
      }
      if (form === 'cuFormTwo') {
        that.roleIndexPageListTwo = []
        that.roleMiniIndexPageListTwo = []
      }

      // 重新初始化首页select
      if (form === 'cuForm') {
        if (!canRemove) {
          that.cuForm.role_ids.push(removeId)
        }
        if (that.cuForm.role_ids) {
          that.cuForm.role_ids.forEach(item => {
            const temp = cloneDeep(that.roles['_' + item] || {})
            if (temp) {
              that.roleIndexPageList.push(temp)
              that.roleMiniIndexPageList.push(temp)
            }
          })
        }
      }
      if (form === 'cuFormTwo') {
        if (!canRemove) {
          that.cuFormTwo.role_ids.push(removeId)
        }
        if (that.cuFormTwo.role_ids) {
          that.cuFormTwo.role_ids.forEach(item => {
            const temp = cloneDeep(that.roles['_' + item] || {})
            if (temp) {
              that.roleIndexPageListTwo.push(temp)
              that.roleMiniIndexPageListTwo.push(temp)
            }
          })
        }
      }
    },

    visibleChangeRole(show) {
      if (!show) {
        this.setRoleIndexPageList()
      }
    },
    changeRole(e) {
      const that = this
      this.setRoleIndexPageList()
    },
    removeRole(e) {
      const that = this
      that.setRoleIndexPageList(false, 'cuForm', !that.roleIsHide(e), e)
    },

    visibleChangeRoleTwo(show) {
      if (!show) {
        this.setRoleIndexPageList(false, 'cuFormTwo')
      }
    },
    changeRoleTwo(e) {
      const that = this
      this.setRoleIndexPageList(false, 'cuFormTwo')
    },
    removeRoleTwo(e) {
      const that = this
      that.setRoleIndexPageList(false, 'cuFormTwo', !that.roleIsHide(e), e)
    },
    roleIsHide(role_id) {
      const that = this
      const isHide = (that.roles['_' + role_id].hide || 0) == 1
      if (isHide) Message.error('业务所需角色，不允许去除用户关联')
      return isHide
    },

    chooseOneDepartment(data) {
      this.cuFormThree.department_list.push({
        id: data.id,
        name: data.p_name,
        job: data.job,
        business: data.business
      })
    },
    choosedDepartment() {
      this.cuFormTwo.department_list = cloneDeep(this.cuFormThree.department_list)
      if (this.cuFormTwo.department_list.length > 0 && this.cuFormTwo.department_list.every(d => !d.main)) {
        this.cuFormTwo.department_list[0].main = true
        this.mainDepartmentId = this.cuFormTwo.department_list[0].id
      }
      this.resetFormThree()
      this.dialogCUThree = false
      this.dialogCULoadingThree = false
    },

    // 重置搜索表单
    searchReset() {
      this.$refs.searchForm.resetFields()
      const params = this.$refs.searchForm.model
      this.listParams = Object.assign(this.listParams, params)
      this.getList()
    },
    // 搜索
    searchSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = this.$refs[formName].model
          if (!params.name) params.name = null
          this.listParams.page = 1
          this.current = 1
          this.listParams = Object.assign(this.listParams, params)
          this.getList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 移除
    deleteRow(index, rows) {
      if (rows[index].main) {
        Message.error('不能删除主部门')
        return
      }
      rows.splice(index, 1)
    },

    // 表单多选
    handleSelectionChange(val) {
      this.selectIds = val.map(item => item.id)
    },
    // 分页 -pageSize改变
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    // 分页 -pageNum改变
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    // 带状态表格
    tableRowClassName({
      row
    }) {
      if (row.is_joined === 0) {
        return 'stop-row'
      }
      return ''
    }
  }
}
</script>
<style scoped>
.search .el-form-item:last-child {
  margin-left: 35px;
}

.el-date-editor > .el-range-separator {
  width: 8% !important;
}

.operation button {
  padding: 8px;
}

.el-pagination {
  margin-top: 40px;
}
</style>
<style lang="scss" scoped>
.app-container {
  .el-table {
    margin-top: 20px;

    .names-tag {
      box-sizing: border-box;
      margin: 3px;
    }

    /deep/ .stop-row {
      color: #bbb !important;
    }
  }
}
</style>
